package colaborativo.ondefica;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONArray;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

public class CriarEvento extends Activity  {
	
	EditText datainicio, datafim, horainicio, horafim,titulo,descricao,contato;
	TextView txt;
	int mYear, mMonth, mDay, mHour, mMinute; 
	private String strdatafim;
	private String strdataini;
	private String strhoraini;
	private String strhorafim;
	Double xc, yc;
	private int reqCode;
	private String ptLoc;
	private String idLugar;
	private String NomeLugar;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Bundle extras = getIntent().getExtras();
		if(extras!=null){
			xc = extras.getDouble("xcenter");
			yc = extras.getDouble("ycenter");
			Log.d("CE.Debug", xc+"/"+yc);
		}
		
		 setContentView(R.layout.activity_criar_evento);
		 datainicio = (EditText) findViewById(R.id.datainicio);
		 datafim = (EditText) findViewById(R.id.datafim);
		 horainicio = (EditText) findViewById(R.id.horainicio);
		 horafim = (EditText) findViewById(R.id.horafim);
		 titulo = (EditText) findViewById(R.id.editTitulo);
		 descricao = (EditText) findViewById(R.id.editDescricao);
		 contato = (EditText) findViewById(R.id.editContato);
	     txt = (TextView) findViewById(R.id.textLocal);
	    
	}
		
	
	public void inserirPonto(View v){
		Intent intent = new Intent(this, SelectPoint.class);
		Bundle pontos = new Bundle();
		
		pontos.putDouble("xcenter", xc);
		pontos.putDouble("ycenter", yc);
		intent.putExtras(pontos);
		startActivityForResult(intent,reqCode);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		  super.onActivityResult(requestCode, resultCode, data);
		  if (requestCode == reqCode && resultCode == RESULT_OK && data != null){
			  Bundle bd = data.getExtras();		  
			  ptLoc = bd.getString("LocalID");
			  Log.d("CE.DEBUG", ptLoc);
			  //local+" ("+idPonto+")"			 
			  String[] fields = ptLoc.split(":");
			  idLugar = fields[1];
			  NomeLugar = fields[0];
			  txt.setText(NomeLugar);
		  }
	}
	
	 public void exibirData(View view) {
		
			final Calendar c = Calendar.getInstance();
	        mYear = c.get(Calendar.YEAR);
	        mMonth = c.get(Calendar.MONTH);
	        mDay = c.get(Calendar.DAY_OF_MONTH);
	
	       if(view == datainicio){
	        DatePickerDialog dpd = new DatePickerDialog(this,
	                new DatePickerDialog.OnDateSetListener() {
	
	                    @Override
	                    public void onDateSet(DatePicker view, int year,
	                            int monthOfYear, int dayOfMonth) {
	                        // Display Selected date in textbox
	                        datainicio.setText(dayOfMonth + "/"
	                                + (monthOfYear + 1) + "/" + year);
	
	                    }
	                }, mYear, mMonth, mDay);
	        dpd.show();
	       }else{
	           DatePickerDialog dpd = new DatePickerDialog(this,
		                new DatePickerDialog.OnDateSetListener() {
		
		                    @Override
		                    public void onDateSet(DatePicker view, int year,
		                            int monthOfYear, int dayOfMonth) {
		                        // Display Selected date in textbox
		                        datafim.setText(dayOfMonth + "/"
		                                + (monthOfYear + 1) + "/" + year);
		
		                    }
		                }, mYear, mMonth, mDay);
		        dpd.show();
	       }
		
	}
	
	 public void exibirHora(View view){
		 final Calendar c = Calendar.getInstance();
         mHour = c.get(Calendar.HOUR_OF_DAY);
         mMinute = c.get(Calendar.MINUTE);
        

         if(view == horainicio){ 
	         TimePickerDialog tpd = new TimePickerDialog(this,
	                 new TimePickerDialog.OnTimeSetListener() {
	
	                     @Override
	                     public void onTimeSet(TimePicker view, int hourOfDay,
	                             int minute) {
	                         horainicio.setText(hourOfDay + ":" + minute);
	                     }
	                 }, mHour, mMinute, false);
	         tpd.show();
         }else{
        	 TimePickerDialog tpd = new TimePickerDialog(this,
                     new TimePickerDialog.OnTimeSetListener() {

                         @Override
                         public void onTimeSet(TimePicker view, int hourOfDay,
                                 int minute) {
                             horafim.setText(hourOfDay + ":" + minute);
                         }
                     }, mHour, mMinute, false);
        	 tpd.show();
         }
         
        
	 }
	 
	public void cadastroEvento(View view) {
		//Conversao CAMPOS
		SimpleDateFormat fmt_data = new SimpleDateFormat("dd/mm/yyyy");
		Date testDate = null;
		try {
		    testDate = fmt_data.parse(datafim.getText().toString());
		}catch(Exception ex){
		    ex.printStackTrace();
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
		strdatafim = formatter.format(testDate);
	     
		testDate = null;
		try {
		    testDate = fmt_data.parse(datainicio.getText().toString());
		}catch(Exception ex){
		    ex.printStackTrace();
		}
		formatter = new SimpleDateFormat("yyyy-mm-dd");
		strdataini = formatter.format(testDate);
		strhoraini = horainicio.getText().toString() + ":00";
		strhorafim = horafim.getText().toString() + ":00";										
		
		new MyAsyncTask().execute("vai!!");
		
	}
	 
	private class MyAsyncTask extends AsyncTask<String, Integer, JSONArray>{
    	JSONArray jSarr;
    	
        @Override
        protected JSONArray doInBackground(String... params) {	        	
        	
        	String qry= "INSERT INTO `evento` (`titulo` ,`descricao` ,`dataInicio` ,`dataFim`"
    				+ ", `horarioInicio` ,`horarioFim` ,`IdGeoPonto` ,`idEvento`) VALUES ( '"
    				+ titulo.getText().toString()+"', '"+descricao.getText().toString()+"', '"+strdataini
    				+"', '"+strdatafim+"', '"+strhoraini+"', '"
    				+strhorafim +"', "+idLugar+", NULL)";
    		Log.d("oM.eV.Query", qry);	    		
    		return jSarr = DbConnection.consulta(qry);	    				        
        }
         
        protected void onPostExecute(JSONArray result){
//	        Log.d("oM.pV.resultado", jSarr.toString());	    		
        	
        	Log.d("oM.eV.Result", "Acabou consulta");
        	finish();
    			        	    			  
        }
        protected void onProgressUpdate(Integer... progress){
//        	progress(progress[0]);
        }
        
        
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.criar_evento, menu);
		return true;
	}
	



}
